import { Module, VuexModule, Action } from "vuex-class-modules";
import { OidcGetUser } from "@/framework/oidc";
import { getAuthCodes, getAuthMenus, getSystemSettings } from "../apis/Account";

// import MenuType from "./menu-type";
import { MenuItem } from "./MenuStore";

@Module({ generateMutationSetters: true })
export default class UserStore extends VuexModule {
  Uid: string; // 当前用户唯一标识
  UserName: string; // 用户名
  UserAvatar: string; // 用户头像
  CompanyName: string; // 企业名称
  CompanyCode: string; // 企业编码
  isAdmin = false; // 是否管理员
  AuthCodes: string[] = []; // 我的权限清单集合
  AuthMenus: MenuItem[] = []; // 我的菜单清单集合
  SysSettings: { [key: string]: any } = {}; // 系统设置

  // 是否具有新消息
  hasMessage = false;

  @Action
  async setHasMessage() {
    this.hasMessage = true;
  }

  @Action
  async UpdateUserInfo() {
    const { profile } = await OidcGetUser();
    if (profile) {
      this.UserName = profile.nickname || profile.name;
      this.UserAvatar = profile.picture;
      this.CompanyCode = profile.companycode;
      this.CompanyName = profile.companyname;
      this.Uid = profile.sub;
      this.isAdmin = profile.role === "SUPER_ADMIN";
      // 加载权限及具有权限的菜单
      const [{ data: authCodes }, { data: authMenus }] = await Promise.all([getAuthCodes(), getAuthMenus()]);
      this.AuthCodes = authCodes;

      const sidebarMenus: MenuItem[] = authMenus.map(m => ({
        code: m.code, // 菜单编码
        pcode: m.codeParent, // 父级编码
        name: m.name, // 菜单名称
        menuType: m.menuType, // 菜单类型 0：submenu; 1：tab-router-view ; 2：dialog-iframe ;3：Sidebar-firame ; 4：tab-iframe
        order: m.order,
        url: m.url,
        description: m.description, // 菜单描述
        isVisibled: m.isVisibled, // 是否显示
        icon: {
          code: m.icon,
          type: m.iconType, // 0:无图标； 1：element-icon ;2：iconfont； 3：custom-icon；4：svg ；5：image-url
          color: m.iconColor,
        },
        isDefault: m.isDefault,
        isFixed: m.isFixed,
        canSetFixed: m.allowSetFixed,
        isHome: m.isHome,
        canClose: m.allowClose,
        options: m.options,
      }));

      this.AuthMenus = sidebarMenus;

      // 加载系统设置
      const { data: sysSettings } = await getSystemSettings();
      Object.keys(sysSettings).forEach(key => {
        this.SysSettings[key] = sysSettings[key];
      });
    }
  }
}
